package com.jlc.o2o.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class ImageUtil {

    private static final SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private static final Random r = new Random();
    //获取水印图片绝对路径
    private static final String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();


    public  static String generateTumbnail(CommonsMultipartFile thumbnail, String tagetAddr){//传入的图片、 相对路径

        //获取随机文件名
        String realFileName =  getRandomFileName();
        //获取后缀名
        String extension = getFileExtension(thumbnail);
        //创建目标路径所涉及到的目录
        makeDirPath(tagetAddr);
        String relativeAddr = tagetAddr + realFileName + extension;
        File dest = new File(PathUtil.getImgBasePath() + relativeAddr);

        try{
               Thumbnails.of(thumbnail.getInputStream()).size(200,200)
                    .watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg"))
                            ,0.25f).outputQuality(0.8f).toFile(dest);

        }catch(Exception e){
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /**
     * 创建目标路径所涉及到的目录, 既/home/work/xiangzi/xx.jpg
     * @param tagetAddr
     */
    private static void makeDirPath(String tagetAddr) {

    String realFileParentPath = PathUtil.getImgBasePath() + tagetAddr;
    File dirPath = new File(realFileParentPath);
        if(!dirPath.exists()){
            dirPath.mkdirs();
        }
    }


    /**
     * 获取数据文件流的扩展名 .jpg  .png
     * @param thumbnail
     * @return
     */
    private static String getFileExtension(CommonsMultipartFile thumbnail) {
        String originalFileName = thumbnail.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }


    /**
     * 生成随机文件名
     * @return
     */
    private static String getRandomFileName() {

        int runnum = r.nextInt(89999) + 10000;
        String nowTimeStr = sDateFormat.format(new Date());
        return nowTimeStr + runnum;
    }


    public static void main(String[] args) throws IOException {


        Thumbnails.of(new File("D:\\img\\zuowei.jpg")
        ).size(200,200).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")),
                0.25f).outputQuality(0.8f)
        .toFile("D:\\img\\zuoweiNew.jpg");
    }
}
